package utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

/**
 * Created by huyongsheng on 2015/3/18.
 * <p/>
 * 用于处理网络相关
 * <p/>
 * 已添加get请求相关
 */
public class NetUtils {
    private static final String TAG = NetUtils.class.getSimpleName();
    public static final int ErrorData = -5000;
    private static final int ErrorJson = -5001;

    private static NetUtils mInstance;
    private static ProgressDialog mProgressDialog;
    private boolean isNeedProgress;

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 联网
     */
    private NetUtils() {

    }

    /**
     * 使用单例模式，确保控件只有一个
     */
    public static NetUtils getInstance(boolean isNeedProgress) {
        if (mInstance == null) {
            mInstance = new NetUtils();
        }
        mInstance.isNeedProgress = isNeedProgress;
        return mInstance;
    }
//
//    /**
//     * 将网络请求、内容解析和等待进度条封装在一起使用
//     */
//    public void get(Context context, RequestParams params, MediaSessionCompat.Callback callBack) {
//        get(context, ConstantUtils.HOST, params, callBack, 0, 10);
//    }

//    /**
//     * 将网络请求、内容解析和等待进度条封装在一起使用
//     */
//    public void getNoCache(Context context, RequestParams params, Callback callBack) {
//        get(context, NetConstant.HOST, params, callBack, 0, 0);
//    }
//
    /**
     * 将网络请求、内容解析和等待进度条封装在一起使用
     */
//    public void get(Context context, String url, RequestParams params, MediaSessionCompat.Callback callBack, int cacheTime, int fileTime) {
//        List<NameValuePair> names = params.getQueryStringParams();
//        callBack.cacheFileName = "";
//        for (NameValuePair name : names) {
//            callBack.cacheFileName = StringUtils.getString(callBack.cacheFileName, name.getName(), ":", name.getValue(), "--");
//        }
////        LogUtils.e(context, TAG, "fileName:", callBack.cacheFileName);
////        callBack.cacheFileName = StringUtils.toMD5(callBack.cacheFileName);
////        LogUtils.e(context, TAG, "fileName-md5:", callBack.cacheFileName);
//        // 如果从文件获取数据
//        if (fileTime > 0) {
//            String fileCache = FileUtils.readStringFromFileCache(context, callBack.cacheFileName);
//            if (!TextUtils.isEmpty(fileCache)) {
//                ResponseInfo<String> info = new ResponseInfo<>(null, fileCache, true);
//                callBack.onSuccess(info);
//            }
//            LogUtils.e(context, TAG, "fileCache:", fileCache);
//        }
//        if (isNetworkConnected(context)) {
//            // 请求网络
//            new HttpUtils().configCurrentHttpCacheExpiry(cacheTime)
//                    .send(HttpRequest.HttpMethod.GET, url, params, callBack);
//            if (isNeedProgress) {
//                mProgressDialog = DialogUtils.showProgressDialog(context);
//            }
//        } else {
//            DialogUtils.showShortPromptToast(context, R.string.network_is_not_available);
//            HttpException e = new HttpException(EMError.NONETWORK_ERROR,"");
//            callBack.dealError(e);
//        }
//    }
//
//    /**
//     * 将网络请求、内容解析和等待进度条封装在一起使用
//     */
//    public abstract static class Callback<Response extends BaseResponse> extends RequestCallBack<String>
//            implements StringToBeanTask.ConvertListener<Response> {
//        private Context mContext;
//        private Class<Response> mClassType;
//        private boolean isFileCache;
//        private String cacheFileName;
//
//        public abstract void onDataSuccess(Response response, boolean isFileCache);
//
//        public void onNetFailed(HttpException e) {
//        }

//        public Callback(Context context, Class<Response> classType) {
//            mContext = context;
//            mClassType = classType;
//            isFileCache = false;
//        }
//
//        @Override  public void onSuccess(ResponseInfo<String> responseInfo) {
//            isFileCache = responseInfo.getAllHeaders() == null;
//            StringToBeanTask<Response> task = new StringToBeanTask<>(mClassType, this);
//            task.execute(responseInfo.result);
//            // 写入缓存
//            FileUtils.writeStringToFileCache(mContext, cacheFileName, responseInfo.result);
//        }
//
//        @Override public void onFailure(HttpException e, String s) {
//            if (mProgressDialog != null && mProgressDialog.isShowing() && !isFileCache) {
//                mProgressDialog.dismiss();
//            }
////            dealError(e);
//        }
//
//        @Override public void onConvertSuccess(Response response) {
//            if (mProgressDialog != null && mProgressDialog.isShowing() && !isFileCache) {
//                mProgressDialog.dismiss();
//            }
//            if (!response.getError()) {
//                onDataSuccess(response, isFileCache);
//            } else {
//                HttpException e = new HttpException(ErrorData, response.getMessage());
////                dealError(e);
//            }
//        }
//
//        @Override public void onConvertFailed(String json) {
//            if (mProgressDialog != null && mProgressDialog.isShowing() && !isFileCache) {
//                mProgressDialog.dismiss();
//            }
//            HttpException e = new HttpException(ErrorJson,"Convert Json Failed" + json);
////            dealError(e);
//        }

//        private void dealError(HttpException e) {
//            switch (e.getExceptionCode()) {
//                case EMError.NONETWORK_ERROR:
//                    DialogUtils.showShortPromptToast(mContext, R.string.network_anomalies);
//                    break;
//                case EMError.USER_ALREADY_EXISTS:
//                    DialogUtils.showShortPromptToast(mContext, R.string.phone_number_has_registered);
//                    break;
//                case EMError.UNAUTHORIZED:
//                    DialogUtils.showShortPromptToast(mContext, R.string.registration_failed_without_permission);
//                    break;
//                case EMError.ILLEGAL_USER_NAME:
//                    DialogUtils.showShortPromptToast(mContext, R.string.illegal_user_name);
//                    break;
//                case ErrorData:
//                    DialogUtils.showShortPromptToast(mContext, e.getMessage());
//                    break;
//                case ErrorJson:
//                    LogForTest.logE(e.getMessage());
//                    break;
//                default:
//                    DialogUtils.showShortPromptToast(mContext, R.string.network_anomalies);
//                    break;
//            }
//            LogUtils.e(mContext, TAG, e);
//            onNetFailed(e);
//        }
//    }
    /**
     * 判断用户是否使用WiFi
     *
     * @param context
     * @return
     */
    public static boolean isWifiNet(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        if (networkINfo != null && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }
    /**
     * 判断用户是否使用的为2G网络
     * GPRS | EDGE 中国移动和中国联通2G ，CDMA 中国电信2G
     *
     * @param context
     * @return
     */
    public static boolean isSecGenerationNet(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null && isMobileNet(context) && (telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_GPRS
                || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE
                || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_CDMA)) {
            return true;
        }
        return false;
    }

    /**
     * 判断用户是否使用3G网络
     * UMTS/HSDPA 中国联通3G，EVDO 中国电信3G
     *
     * @param context
     * @return
     */
    public static boolean isThirdGenerationNet(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null && isMobileNet(context) && (telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS
                || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA
                || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_EVDO_0)) {
            return true;
        }
        return false;
    }

    /**
     * 判断用户是否为移动网络
     *
     * @param context
     * @return
     */
    public static boolean isMobileNet(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        if (networkINfo != null
                && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            return true;
        }
        return false;
    }
}